package hejie.admin.service.impl;

import java.util.List;

import hejie.admin.dao.GuaranteeWayDao;
import hejie.admin.service.GuaranteeWayService;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;


import publics.model.GuaranteeWay;
import publics.util.Page;


@Component("guaranteeWayService")
public class GuaranteeWayServiceImpl implements GuaranteeWayService{
	
	GuaranteeWayDao guaranteeWayDao;
	
	public GuaranteeWayDao getGuaranteeWayDao() {
		return guaranteeWayDao;
	}	
	@Resource(name="guaranteeWayDao")
	public void setGuaranteeWayDao(GuaranteeWayDao guaranteeWayDao) {
		this.guaranteeWayDao = guaranteeWayDao;
		System.out.println("guaranteeWayDaoImpl inject in GuaranteeWayServiceImpl");
	}

	public Integer saveGuaranteeWay(GuaranteeWay gway) {	
		List<GuaranteeWay> gwayName = guaranteeWayDao.findByName(gway.getName());	
		List<GuaranteeWay> gwayNum = guaranteeWayDao.findByNum(gway.getNum());	
		if(gwayName.size() == 0&&gwayNum.size()==0){
			return guaranteeWayDao.save(gway);		
		}
		else 			
		   return null;
	}

	public Page findByPage(Page page) {
		String sql = "from GuaranteeWay g";		 
		if(page.getConditions().size() > 0){//这里为模糊查询的 sql 语句拼接
			sql = sql + " where ";  
			for(int i = 0; i < page.getConditions().size(); ){
				sql = sql + "( g.name like '%"+page.getConditions().get(i)+"%'"
				+" or g.num like '%"+page.getConditions().get(i)+"%' ) ";
				//每次上面两个属性只有匹配到的才能取到值，不然为%
				i++;
				if(i < page.getConditions().size()){// 如果条件不止一个 进行连续拼接
					sql = sql + " and ";
				}
			}
		}
		System.out.println("sql ="+sql);
		
		int pageSize = page.getLimit();
		int offset = page.getStart();//-1)*pageSize;
		page.setRoot(guaranteeWayDao.findByPage(sql,offset,pageSize));//把查询结果放入root中
		page.setTotalProperty(guaranteeWayDao.findByCount(sql));   //把数据总数放入totalProperty中
		return page;
	}

	public boolean updateGuaranteeWay(GuaranteeWay gway) {
//		List<GuaranteeWay> gwaysName = guaranteeWayDao.findByName(gway.getName());		
//		List<GuaranteeWay> gwaysNum = guaranteeWayDao.findByNum(gway.getNum());	
//		if(gwaysName.size() == 0||gwaysNum.size()==0){
//			return false;
//		}
//		else 	
		return guaranteeWayDao.update(gway);
		
	}

	public boolean deleteGuaranteeWay(Integer id) {
		System.out.println("service里 guaranteeWayId="+id);
		return guaranteeWayDao.deleteById(id);
	} 	
}
